package com.example.interview.ch03;

/**
 * synchronized(*.class)代码块
 *
 * @author anin
 * @date 2022/4/27 10:54 AM
 */
public class Test4 {

    /*
     * 同步synchronized(*.class)代码块的作用其实和synchronized static方法作用一样。
     * Class锁对类的所有对象实例起作用。
     */

    public static void main(String[] args) {
        Test4ObjectService objectService1 = new Test4ObjectService();
        Test4ObjectService objectService2 = new Test4ObjectService();
        new Thread(()->{
            objectService1.methodA();
        }).start();

        new Thread(()->{
            objectService2.methodB();
        }).start();
    }
}

class Test4ObjectService {
    public void methodA(){
        try {
            synchronized (ObjectService.class) {
                System.out.println("methodA begin 线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
                Thread.sleep(3000);
                System.out.println("methodA end   线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void methodB(){
        synchronized (ObjectService.class) {
            System.out.println("methodB begin 线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
            System.out.println("methodB end   线程名称:"+Thread.currentThread().getName()+" times:"+System.currentTimeMillis());
        }
    }
}
